import requests

from tools.db_model_tool import config_path
from tools.yaml_handle import ReadYaml


class DingTalkToken:
    def __init__(self, app_key, app_secret, ):
        self.app_key = app_key
        self.app_secret = app_secret
        self.token_url =ReadYaml(config_path ).read_yaml["DingTalkSubscriptionRobot"]["TokenUrl"]
        self.token = None

    def get_token(self):
        if not self.token:
            params = {
                'appkey': self.app_key,
                'appsecret': self.app_secret
            }
            response = requests.get(self.token_url, params=params)
            if response.status_code == 200:
                data = response.json()
                if data.get('errcode') == 0:
                    self.token = data.get('access_token')
                else:
                    raise Exception(f"Error getting token: {data.get('errmsg')}")
            else:
                raise Exception(f"Request failed with status code {response.status_code}")
        return self.token
